﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace ConfigManager.Core.Instructions
{
    public class SetValueInstruction : XmlInstruction
    {
        private string _xpath;
        private string _value;

        #region Properties
        /// <summary>
        /// Gets or sets the xpath.
        /// </summary>
        /// <value>The xpath.</value>
        public string XPath
        {
            get { return _xpath; }
            set { _xpath = value; }
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>The value.</value>
        public string Value
        {
            get { return _value; }
            set { _value = value; }
        }
        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="SetValueInstruction"/> class.
        /// </summary>
        /// <param name="xmlDoc">The XML doc.</param>
        /// <param name="node">The node.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="data">The data.</param>
        public SetValueInstruction(XmlDocument xmlDoc, XmlNode node, IDictionary<string, string> parameters)
            : base ( xmlDoc, node, parameters)
        {
            if (parameters.ContainsKey("xpath") == false)
                throw new ArgumentException(String.Format(ResourceStrings.MissingParameter, "xpath"));

            if (parameters.ContainsKey("value") == false)
                throw new ArgumentException(String.Format(ResourceStrings.MissingParameter, "value"));

            this.XPath = parameters["xpath"];
            this.Value = parameters["value"];
        }

        /// <summary>
        /// Runs this instruction.
        /// </summary>
        public override void Run()
        {
            if (PassesConditions())
            {
                XmlNode node = XmlDoc.SelectSingleNode(_xpath);
                if (node != null)
                    node.InnerText = _value;
            }

            base.Run();
        }

    }
}
